<template>
  <div class="edit-project">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/projects' }">项目管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/projects/${route.params.id}` }">项目详情</el-breadcrumb-item>
        <el-breadcrumb-item>编辑项目</el-breadcrumb-item>
      </el-breadcrumb>
      <h1>编辑项目</h1>
    </div>

    <div class="content-container">
      <el-card>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          v-loading="loading"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入项目名称" />
          </el-form-item>

          <el-form-item label="项目描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入项目描述"
            />
          </el-form-item>

          <el-form-item label="项目状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择项目状态">
              <el-option label="进行中" value="active" />
              <el-option label="已暂停" value="paused" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>

          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="选择开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="选择结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              保存修改
            </el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
// import { projectApi } from '@/api/project'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const submitting = ref(false)

const form = reactive({
  name: '',
  description: '',
  status: 'active',
  startDate: '',
  endDate: ''
})

const rules: FormRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '项目名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入项目描述', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ]
}

const loadProject = async () => {
  try {
    loading.value = true
    const projectId = route.params.id as string
    
    // 模拟数据加载
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 这里应该调用真实的API
    // const response = await projectApi.getProject(projectId)
    // Object.assign(form, response.data)
    
    // 模拟数据
    const mockData = {
      '1': {
        name: '电商平台重构项目',
        description: '对现有电商平台进行全面重构，提升用户体验和系统性能',
        status: 'active',
        startDate: '2024-01-01',
        endDate: '2024-06-30'
      },
      '2': {
        name: '移动端APP开发',
        description: '开发iOS和Android移动端应用，实现核心业务功能',
        status: 'active',
        startDate: '2024-02-01',
        endDate: '2024-08-31'
      },
      '3': {
        name: '数据分析平台',
        description: '构建企业级数据分析平台，支持实时数据处理和可视化',
        status: 'paused',
        startDate: '2024-03-01',
        endDate: '2024-12-31'
      }
    }
    
    const projectData = mockData[projectId as keyof typeof mockData]
    if (projectData) {
      Object.assign(form, projectData)
    } else {
      ElMessage.error('项目不存在')
      router.push('/projects')
    }
  } catch (error) {
    console.error('加载项目信息失败:', error)
    ElMessage.error('加载项目信息失败')
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该调用真实的API
    // await projectApi.updateProject(route.params.id as string, form)
    
    ElMessage.success('项目更新成功')
    router.push(`/projects/${route.params.id}`)
  } catch (error) {
    console.error('更新项目失败:', error)
    ElMessage.error('更新项目失败')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  ElMessageBox.confirm(
    '确定要取消编辑吗？未保存的修改将会丢失。',
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning'
    }
  ).then(() => {
    router.push(`/projects/${route.params.id}`)
  }).catch(() => {
    // 用户取消
  })
}

onMounted(() => {
  loadProject()
})
</script>

<style scoped>
.edit-project {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 10px 0;
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

.content-container {
  max-width: 800px;
}

.el-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input,
.el-select,
.el-date-picker {
  width: 100%;
}

.el-textarea {
  width: 100%;
}
</style>